import {defineStore} from 'pinia';



// 定义窗口状态的接口
interface WindowState {
    windowWidth: number | null;
    windowHeight: number | null;
}

export const useWindowStore = defineStore('window', {
    state: (): WindowState => ({
        windowWidth: null,
        windowHeight: null
    }),
    actions: {
        setWindowWidth(width: number) {
            this.windowWidth = width; // 设置窗口宽度
            // console.log("windows width: ", width)
        },
        // 检查窗口大小并返回布尔值
        checkWindowSize(): boolean {
            return this.windowWidth !== null && this.windowWidth < 970;
        },
        sidebarWindowSize(): boolean {
            return this.windowWidth !== null && this.windowWidth < 790;
        },
        observeElementMiddle(selector: Element | null, callback: (isInMiddle: boolean, element: Element) => void, threshold = 1, rootMargin: string = '0px') {
            if (!selector) {
                console.error(`元素 ${selector} 未找到`);
                return;
            }
            const observer = new IntersectionObserver( entries => {
                entries.forEach(entry => {
                    const visibleRatio = entry.intersectionRatio;
                    console.log(visibleRatio)
                    const isInMiddle = visibleRatio >= threshold;
                    if (isInMiddle){
                        callback(isInMiddle, entry.target)
                        observer.unobserve(entry.target)
                    }
                })

            }, {
                threshold: [threshold],
                root: null,
                rootMargin: rootMargin,
            })
            observer.observe(selector)
            return observer;
        }
    },
});
